#coding:utf-8
import time,os,logging
from str2arry import str2arry
from serialCom import serialCom
from checkSum import hex_checksum
from time import strftime

FILE = os.getcwd()          #返回当前目录的路径
#logging基础配置，文件名为 os.path.join里面的两个值想加个，输出等级为≥DEBUG级别
logging.basicConfig(filename = os.path.join(FILE,'log.txt'),level = logging.DEBUG,
                    format='%(asctime)s %(filename)s [line:%(lineno)d] %(levelname)s %(message)s')

def setTime():
    print '----------------------------------------------------------'
    print 'case6 设置时钟' + '\n' + '                                    '


    # 读取表号
    meterIDread = (
        ''.join(('FE FE FE FE FE 68 AB 57 58 AA AA AA AA AA F2 77 88 99 55 03 00 03 81 0A 01 85 16').split()))
    ID = serialCom(meterIDread, 35)[28:38]
    ID = str2arry(ID)                                #返回值为数组
    logging.debug('获取表号 %s 用于设置参数',''.join(ID))
    # 读取表号


    logging.debug('*****case6 设置时钟*****')
    # 设置时钟，格式
    frameHead = 'FE FE FE FE FE 68 AB 57 58'
    # ID
    frameBody= 'F9 77 88 99 55 04 00 0C A0 15 01 00 00 '
    pcTime=str2arry(strftime("%Y%m%d%H%M%S"))
    time1=str2arry('20170410121212')
    timeArry=[time1,pcTime]

    # 校验和
    # 16

    #读取时钟、累积量等，格式
    frameHead_Read = 'FE FE FE FE FE 68 AB 57 58'
    #ID
    frameBody_Read = 'F2 77 88 99 55 21 00 03 90 0F 01'
    #校验和
    #16

    for i in timeArry:
        frameData = frameHead.split() + ID + frameBody.split() + i
        frameCheckSum = hex_checksum(frameData[5:])
        frame = ''.join(frameData + frameCheckSum) + '16'
        serialCom(frame)   #发送时间命令帧


        frameData_Read =frameHead_Read.split()+ID+frameBody_Read.split()
        frameCheckSum_Read=hex_checksum(frameData_Read[5:])
        frame_Read=''.join(frameData_Read+frameCheckSum_Read)+'16'
        frame_Receive=serialCom(frame_Read,51)
        x = str2arry(frame_Receive[88:96])
        print x

        # print frame_Read
        if x==i[-6:-2]:
            print '设置时间%s正确'%(' '.join(i))
            logging.debug('设置时间%s正确'%(' '.join(i)))
        else:
            print '设置时间%s正确'%(' '.join(i))
            logging.debug('设置时间%s错误' % (' '.join(i)))


    softVersion = '-'.join(frame_Receive[80:84][1:])
    hardVersion = '-'.join(frame_Receive[84:88][1:])
    print '硬件版本%s,软件版本%s'%(hardVersion,softVersion)
    logging.debug('硬件版本%s,软件版本%s'%(hardVersion,softVersion))
